from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import Article
import re

page_num = 5  # 每页显示数量


def get_blogs_by_category(request, category, template_name):
    # 获取指定类别的博客文章
    blogs = Article.objects.filter(classes=category)
    hots = Article.objects.filter(hot=True)
    blogs_list = blogs.order_by('-publish_date')
    paginator = Paginator(blogs_list, page_num)
    page = request.GET.get('page')
    try:
        blogs = paginator.page(page)
    except PageNotAnInteger:
        blogs = paginator.page(1)
    except EmptyPage:
        blogs = paginator.page(paginator.num_pages)
    return render(request, template_name, {'blogs': blogs, 'hots': hots})


def get_index(request):
    tops = Article.objects.filter(top=True)
    hots = Article.objects.filter(hot=True)
    blogs_list = Article.objects.order_by('-publish_date')
    paginator = Paginator(blogs_list, page_num)
    page = request.GET.get('page')
    try:
        blogs = paginator.page(page)
    except PageNotAnInteger:
        blogs = paginator.page(1)
    except EmptyPage:
        blogs = paginator.page(paginator.num_pages)
    return render(request, 'index.html', {'blogs': blogs, 'tops': tops, 'hots': hots})


def detail(request, **args):
    num = request.get_full_path()
    num = re.findall('/(.*?)/', num)
    num = int(num[0])
    # print(num)
    blogs = Article.objects.all().filter(article_id=num)
    hots = Article.objects.all().filter(hot=True)
    return render(request, 'blog-single.html', {'blogs': blogs, 'hots': hots})


def get_blogs(request):
    blogs = Article.objects.order_by('-publish_date')
    return render(request, 'blog-single.html', {'blogs': blogs})


def get_ielts(request):
    return get_blogs_by_category(request, '雅思', 'IELTS.html')


def get_cet(request):
    return get_blogs_by_category(request, 'CET4/6', 'CET.html')


def get_tem(request):
    return get_blogs_by_category(request, 'TEM4/8', 'TEM.html')


def get_bec(request):
    return get_blogs_by_category(request, 'BEC', 'BEC.html')


def get_toefl(request):
    return get_blogs_by_category(request, '托福', 'TOEFL.html')


def get_master(request):
    return get_blogs_by_category(request, '考研英语', 'master.html')
